package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yjy
 * @since 2024-10-25
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 根据id查询店铺信息
     * @param id
     * @return
     */
    public Result queryShopById(Long id) {
        // 1.从redis查询商户缓存  spring cache复习一下
        String shopJson = stringRedisTemplate.opsForValue().get("cache:shop:" + id);
        //2.判断是否存在
        if(StrUtil.isNotBlank(shopJson)){//只有在有字符串的情况才是true null,"\t\n",""这三个都是false
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            //3.存在,直接返回
            return Result.ok(shop);
        }
        //命中的是否是空值 要么是null,要么是""
        if(shopJson != null){//不等于null,说明redis中存储的是null值
            return Result.fail("商户不存在");
        }
        //NULL是缓存中没有找到要去数据库中找,""是找到了但是内容为空直接返回错误

        //4.不存在,根据id查询数据库
        Shop shop = this.getById(id);

        //5.不存在,返回错误
        if(shop == null){
            //将空值存储redis
            stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
            return Result.fail("商户不存在");
        }
        //6.存在,写入redis
        stringRedisTemplate.opsForValue().set("cache:shop:" + id, JSONUtil.toJsonStr(shop), RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);

        //7.返回商户信息
        return Result.ok(shop);
    }

    /**
     * 更新商户信息
     * @param shop
     * @return
     */
    @Transactional
    public Result update(Shop shop) {
        Long id = shop.getId();
        if(id == null){
           return Result.fail("商户id不能为空");
        }
        //1.更新数据库
        updateById(shop);
        //2.删除缓存
        stringRedisTemplate.delete("cache:shop:" + shop.getId());//删除过程中如果抛异常,事务会回滚
        return Result.ok();
    }


}
